package com.bungarus.ratelimit;

import com.bungarus.group.cachestore.CacheStore;
import com.bungarus.group.cachestore.CacheTransformerEx;
import com.bungarus.group.cachestore.StoreColumn;
import com.bungarus.group.cachestore.StoreRow;
import org.springframework.stereotype.Component;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by tang on 2019/11/1.
 */
@Component
public class RateLimitCacheTransformer implements CacheTransformerEx<RateLimit> {
    @Override
    public String getCacheTableName() {
        return "ratelimit";
    }

    @Override
    public StoreRow transform(RateLimit source) {
        Set<StoreColumn> columns = new LinkedHashSet<>();

        StoreColumn column = new StoreColumn();
        column.setColumnName(source.getField());
        column.setColumnValue(source.getValue());
        columns.add(column);

        return StoreRow.newBuilder()
                .id(CacheStore.ofUniqueId(getCacheTableName(), source.getKey()))
                .table(getCacheTableName())
                .values(columns)
                .build();
    }

    @Override
    public RateLimit reverse(StoreRow row) {
        throw new RuntimeException("Access not supported");
    }

    @Override
    public List<RateLimit> reverse2List(StoreRow row) {
        return row.getRowValues().stream()
            .map(storeColumn -> {
                return new RateLimit(storeColumn.getColumnName(), storeColumn.getColumnValue(), "");
            }).collect(Collectors.toList());
    }
}
